package com.zhdl.modules.autopick.service.impl;

import cn.hutool.json.JSONUtil;
import com.google.common.io.Files;
import com.project.common.util.DelayUtil;
import com.zhdl.hardware_modules.service.impl.DeviceServiceImpl;
import com.zhdl.modules.autopick.ProcessControl;
import com.zhdl.modules.autopick.entity.CameraCoordinate;
import com.zhdl.modules.autopick.repository.CameraRepository;
import com.zhdl.modules.autopick.service.CameraService;
import com.zhdl.modules.tools.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.StandardCopyOption;
import java.util.Optional;

import static com.zhdl.modules.autopick.ProcessControl.isRunning;

@Slf4j
@Service
public class CameraServiceImpl implements CameraService {

    final int[] pickInitLocation = new int[]{1593787, -1171282, 1118479};
    private final int horizontalCount = 3;
    private final int verticalCount = 6;
    private final int floorCount = 5;
    private final int boxLength = 800 * 1000;
    private final int boxWidth = 400 * 1000;
    private final int boxHeight = 200 * 1000;
    int[] pickCurrentLocation = new int[3];
    private int position = 0;

    @Resource
    private CameraRepository cameraRepository;

    /**
     * 相机拍照
     */
    @Override
    public void takePhoto() {

        try {
            String code = HttpClientUtil.get("http://localhost:8081/api/v1" + "/one/shot/");
            log.info("code: " + code);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        DelayUtil.delayedExecution(200, () -> {
            File file = new File("E:\\BaiduSyncdisk\\project\\photo");//输入要删除文件目录的绝对路径
            File[] files = file.listFiles();
            for (File value : files) {
                // 删除子文件
                if (value.isFile()) {
                    boolean delete = value.delete();
                    log.info("当前文件已经删除---" + value.getName() + "删除结果为" + delete);
                }
            }
            /* 将结果删掉为空 */
            String pathResult = "E:\\BaiduSyncdisk\\project\\result\\subworldauto.txt";
            File fileResult = new File(pathResult);
            boolean delete = fileResult.delete();
            log.info("删除文件夹成功结果" + delete);

            DelayUtil.delayedExecution(4000, () -> {
                try {
                    String code = HttpClientUtil.get("http://localhost:8081/api/v1" + "/one/shot/");
                    log.info("code: " + code);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        });

        log.info("通知相机拍照");
    }

    /**
     * 获取拍照结果
     */
    @Override
    public void getComputeResult() {
        try {
            Optional<CameraCoordinate> byId = cameraRepository.findById(1);
            CameraCoordinate coordinate = byId.get();
            File file = new File("E:\\BaiduSyncdisk\\project\\result\\subworldauto.txt");
            String string = Files.toString(file, Charset.defaultCharset());
            /*如果结果为空,则直接return*/
            if (string.isEmpty()) {
                isRunning = false;
                return;
            }
            if (coordinate.getFlorNum() != 8) {
                ProcessControl.orationType = -1;
                coordinate.setFlorNum(coordinate.getFlorNum() + 1);
            } else {
                coordinate.setFlorNum(1);
            }
            coordinate.setBagNum(0);
            coordinate.setCameraParam(string);
            cameraRepository.save(coordinate);
            log.info(string + "result");
//        } catch (MWException | IOException e) {
        } catch (Exception e) {
            /* 如果抛出异常，则剪切照片，重试 */
            String path = "E:\\BaiduSyncdisk\\project\\photo\\";
            File file = new File(path);
            File[] files = file.listFiles();
            String currentFileName = files[0].getName();

            File file1 = new File(path + currentFileName);
            File file2 = new File("E:\\BaiduSyncdisk\\project\\backupPhoto\\" + currentFileName);
            try {
                java.nio.file.Files.move(file1.toPath(), file2.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e1) {
                log.info(e1.getMessage());
            }
            log.info("当前照片识别失败");
            isRunning = false;
        }
        log.info("拍照拿到照片 计算机器人需要移动坐标");
    }

    public void getCurrentLocation() {
        pickCurrentLocation[0] = pickInitLocation[0] + (position % horizontalCount) * boxLength;
        pickCurrentLocation[1] = pickInitLocation[1] + ((position % (horizontalCount * verticalCount)) / horizontalCount) * boxWidth;
        pickCurrentLocation[2] = pickInitLocation[2] + (position / (horizontalCount * verticalCount)) * boxHeight;
        position++;
        log.info("剩余袋数" + (horizontalCount * verticalCount * floorCount - position) + "-------------当前料袋位置 position" + position + ">>>>" + JSONUtil.toJsonStr(pickCurrentLocation));
    }

    public void getCameraLocation() {
    }

}
